package com.zzg.util;

import java.lang.reflect.Field;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.sun.org.apache.bcel.internal.generic.NEW;

public class JDBCUtil {
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	private static QueryRunner runner = new QueryRunner(dataSource);
	
	
	public static <T> List<T> queryList(Class clazz,String sql,Object... anyone){
		try {
			return runner.query(sql,new BeanListHandler<T>(clazz),anyone);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static <T> T queryOne(Class clazz,String sql,Object... anyone){
		try {
			return runner.query(sql, new BeanHandler<T>(clazz),anyone);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询行数
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int queryCount(String sql,Object...params){
		try {
			return runner.query(sql,new ResultSetHandler<Integer>(){

				@Override
				public Integer handle(ResultSet rs) throws SQLException {
					//将数据库游标指向第一行
					rs.next();
					//返回行数()
					return rs.getInt(1);
				}
			},params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static int update(String sql,Object...anyone){
		try {
			return runner.update(sql,anyone);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	
}
